package com.yue92.datalife.controller.v1;

import com.yue92.datalife.common.CodeEnum;
import com.yue92.datalife.common.GroupCreate;
import com.yue92.datalife.common.GroupUpdate;
import com.yue92.datalife.exception.UncheckedException;
import com.yue92.datalife.helper.RecordHelper;
import com.yue92.datalife.model.RecordItem;
import com.yue92.datalife.model.RecordItemExtra;
import com.yue92.datalife.model.User;
import com.yue92.datalife.request.RecordItemExtraReq;
import com.yue92.datalife.response.RecordItemExtraIndexRes;
import com.yue92.datalife.response.RecordItemExtraRes;
import com.yue92.datalife.response.RecordItemRes;
import com.yue92.datalife.response.ResponseResource;
import com.yue92.datalife.service.IRecordItemExtraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

import static com.yue92.datalife.common.Constant.CURRENT_USER_ATTRIBUTE;

@RestController
@RequestMapping(value = "/api/v1/record-item-extras", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class RecordItemExtraController {

    @Autowired
    private RecordHelper recordHelper;

    @Autowired
    private IRecordItemExtraService recordItemExtraService;

    @GetMapping("")
    public ResponseResource<RecordItemExtraIndexRes> index(@RequestParam("record_item_id") Long recordItemId, @RequestAttribute(CURRENT_USER_ATTRIBUTE) User currentUser) {
        RecordItem recordItem = recordHelper.checkAndGetRecordItem(recordItemId, currentUser);

        List<RecordItemExtra> recordItemExtraList = recordItemExtraService.getAllByRecordItemId(recordItemId);

        List<RecordItemExtraRes> recordItemExtraResList = new ArrayList<>();
        recordItemExtraList.forEach(extra -> {
            recordItemExtraResList.add(RecordItemExtraRes.builder()
                    .id(extra.getId())
                    .recordDate(extra.getRecordDate().toString())
                    .value(extra.getValue())
                    .comment(extra.getComment())
                    .build()
            );
        });

        RecordItemExtraIndexRes res = RecordItemExtraIndexRes.builder()
                .recordItem(RecordItemRes.builder()
                        .id(recordItem.getId())
                        .recordDate(recordItem.getRecordDate().toString())
                        .value(recordItem.getValue())
                        .comment(recordItem.getComment())
                        .build())
                .extras(recordItemExtraResList).build();

        return ResponseResource.success(res);
    }

    @PostMapping("")
    public ResponseResource<?> create(@Validated({GroupCreate.class}) @RequestBody RecordItemExtraReq recordItemExtraReq, @RequestAttribute(CURRENT_USER_ATTRIBUTE) User currentUser) {
        RecordItem recordItem = recordHelper.checkAndGetRecordItem(recordItemExtraReq.getRecordItemId(), currentUser);

        RecordItemExtra recordItemExtra = new RecordItemExtra();
        recordItemExtra.setRecordItemId(recordItem.getId());
        recordItemExtra.setRecordDate(LocalDate.parse(recordItemExtraReq.getRecordDate()));
        recordItemExtra.setValue(recordItemExtraReq.getValue());
        recordItemExtra.setComment(recordItemExtraReq.getComment());

        recordItemExtraService.save(recordItemExtra);

        return ResponseResource.success(new HashMap<String, Object>() {{
            put("id", recordItemExtra.getId());
        }});
    }

    @PutMapping("/{id}")
    public ResponseResource<?> update(@PathVariable("id") Long id, @Validated({GroupUpdate.class}) @RequestBody RecordItemExtraReq recordItemExtraReq, @RequestAttribute(CURRENT_USER_ATTRIBUTE) User currentUser) {
        Optional<RecordItemExtra> recordItemExtraOptional = recordItemExtraService.get(id);
        if (!recordItemExtraOptional.isPresent()) {
            throw new UncheckedException(CodeEnum.FAILURE, "recordItemExtra not exist");
        }

        RecordItemExtra recordItemExtra = recordItemExtraOptional.get();

        recordHelper.checkAndGetRecordItem(recordItemExtra.getRecordItemId(), currentUser);

        recordItemExtra.setRecordDate(LocalDate.parse(recordItemExtraReq.getRecordDate()));
        recordItemExtra.setValue(recordItemExtraReq.getValue());
        recordItemExtra.setComment(recordItemExtraReq.getComment());

        recordItemExtraService.save(recordItemExtra);

        return ResponseResource.success();
    }

    @DeleteMapping("/{id}")
    public ResponseResource<?> delete(@PathVariable("id") Long id, @RequestAttribute(CURRENT_USER_ATTRIBUTE) User currentUser) {
        Optional<RecordItemExtra> recordItemExtraOptional = recordItemExtraService.get(id);
        if (!recordItemExtraOptional.isPresent()) {
            throw new UncheckedException(CodeEnum.FAILURE, "recordItemExtra not exist");
        }

        RecordItemExtra recordItemExtra = recordItemExtraOptional.get();

        recordHelper.checkAndGetRecordItem(recordItemExtra.getRecordItemId(), currentUser);

        recordItemExtraService.remove(recordItemExtra.getId());

        return ResponseResource.success();
    }
}
